import streamlit as st
import pandas as pd
import os
import zipfile
import rarfile
import shutil

import sys
import os

# 获取当前文件所在目录的上一级目录路径
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 将上一级目录路径添加到系统路径中
sys.path.append(parent_dir)

from langchain_exercise_correction import ExerciseCorrection





def handle_compressed_file_upload(upload_file):
    if upload_file:
        # 定义保存数据的文件夹路径
        data_folder = "data"
        os.makedirs(data_folder, exist_ok=True)

        # 获取上传文件的文件名（不包含路径）
        file_name = os.path.basename(upload_file.name)

        # 创建与文件同名的文件夹路径（不含扩展名）
        unzip_folder_path = os.path.join(data_folder, os.path.splitext(file_name)[0])

        # 如果同名文件夹已存在，先删除它及其所有内容
        if os.path.exists(unzip_folder_path):
            shutil.rmtree(unzip_folder_path)

        # 保存文件到data文件夹
        file_path = os.path.join(data_folder, file_name)
        with open(file_path, "wb") as f:
            f.write(upload_file.getbuffer())

        try:
            if file_name.endswith(".zip"):
                # 解压Zip文件
                with zipfile.ZipFile(file_path, 'r') as zip_ref:
                    for info in zip_ref.infolist():
                        # 假设文件名是UTF - 8编码，将其转换为正确的编码
                        info.filename = info.filename.encode('cp437').decode('gbk')
                        zip_ref.extract(info, unzip_folder_path)
                    #zip_ref.extractall(unzip_folder_path)
                st.success(f"压缩包已成功解压到 {unzip_folder_path}")
                return unzip_folder_path
            elif file_name.endswith(".rar"):
                # 解压Rar文件
                with rarfile.RarFile(file_path) as rar_ref:
                    rar_ref.extractall(unzip_folder_path)
                st.success(f"压缩包已成功解压到 {unzip_folder_path}")
                return unzip_folder_path
        except Exception as e:
            st.error(f"解压出错，请重新上传。错误信息：{str(e)}")
            return None
    else:
        st.warning("请先上传压缩包。")
        return None


result_dataframe = pd.DataFrame()


@st.cache_data
def create_and_update_df():
    # result_dataframe = pd.DataFrame()
    return result_dataframe


# result_dataframe = create_and_update_df()
# st.dataframe(result_dataframe)


def refresh_dataframe(row):
    st.write(row)
    global result_dataframe
    result_dataframe = create_and_update_df()
    result_dataframe = pd.concat([result_dataframe, pd.DataFrame([row])], ignore_index=True)
    # st.rerun()


def main():

    st.title("Python classroom exercise correction expert")

    # 题目输入框
    question = st.text_area("题目", "")

    # 初始程序输入框
    original = st.text_area("初始程序", "")

    # 参考答案文件选择框
    right_answer = st.text_area(" 参考答案", "")

    # 班级文件夹路径选择框
    zip_file = st.file_uploader("上传班级作业压缩包（支持Zip和Rar）", type=["zip", "rar"])
    st.dataframe(result_dataframe)
    # 开始批改按钮
    if st.button("开始批改"):
        floder = handle_compressed_file_upload(zip_file)
        if question.strip() and right_answer.strip() and floder:
            exercise_correction = ExerciseCorrection(floder, question, right_answer, original.strip())
            exercise_correction.handle_model_response = refresh_dataframe
            exercise_correction()
        else:
            st.write("题目和参考答案不能为空,同时必须先上传班级作业压缩包。")
        # # 这里开始进行批改逻辑，目前只是占位
        # handle_compressed_file_upload(zip_file)
        # result = {"题目": question, "初始程序": original, "批改结果": "待完善"}
        #
        #


if __name__ == "__main__":
    main()